package rng

import (
	"crypto/sha512"
	"fmt"
	"github.com/shopspring/decimal"
	"strconv"
	"strings"
	"wzgames/internal/constant"
	"wzgames/pkg/utils/byteutil"
	"wzgames/pkg/utils/calcutil"
)

const ChunkSize int = 4

func CalculateHash(servSeed, clientSeed string, chunkSize, limit int) []float64 {
	return CalculateHashWithRound(servSeed, clientSeed, chunkSize, limit, 0)
}

func CalculateHashWithRound(servSeed, clientSeed string, chunkSize, limit, roundId int) []float64 {
	r, _ := CalculateHashWithRoundAndRetHash(servSeed, clientSeed, chunkSize, limit, roundId)
	return r
}

func CalculateHashWithRoundAndRetHash(servSeed, clientSeed string, chunkSize, limit, roundId int) ([]float64, string) {
	var sb strings.Builder
	sb.WriteString(servSeed)
	sb.WriteString(clientSeed)
	if roundId > 0 {
		sb.WriteString(constant.Colon)
		sb.WriteString(strconv.FormatInt(int64(roundId), 10))
	}
	sum := sha512.Sum512(byteutil.StringToSliceByte(sb.String()))
	return CalculateNumbers(sum, chunkSize, limit), fmt.Sprintf("%x", sum)
}

func CalculateNumbers(byteArr [64]byte, chunkSize, limit int) []float64 {
	bytesArray := ChunkArray(byteArr, chunkSize, limit)

	var numbers []float64

	for i := 0; i < len(bytesArray); i++ {
		numbers = append(numbers, BytesToFloat(bytesArray[i]))
	}

	return numbers
}

func DiceResult(num float64) float64 {
	v1 := decimal.NewFromFloat(num).Mul(decimal.NewFromInt(10001))
	v1 = v1.Div(calcutil.BaseCoefficient)
	f, _ := v1.Float64()
	return calcutil.RoundFloor(f)
}

func RouletteResult(num float64, numbers int32) int32 {
	v1 := decimal.NewFromFloat(num).Mul(decimal.NewFromInt32(numbers))
	return int32(v1.IntPart())
}
